<template>
  <div class="apartment-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">

        <el-form-item>
          <el-select
            v-model="searchForm.districtId"
            placeholder="请选择区域"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in districtOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" style="width: 100px"
            >查询</el-button
          >
          <el-button @click="resetSearch" style="width: 100px">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-section">
      <el-button type="primary" @click="handleAdd">新增门店</el-button>
      <el-button type="success" @click="handleImport">批量导入</el-button>
      <el-button type="warning" @click="handleExport">批量导出</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        class="fixed-height-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="名称" min-width="120" align="center" />
        <el-table-column
          prop="addressDetail"
          label="详细地址"
          min-width="200"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="freeRoomCount"
          label="空闲房间数"
          width="100"
          align="center"
        >
          <template #default="scope">
            <span
              :class="{ 'room-count': true, 'low-count': scope.row.freeRoomCount < 5 }"
            >
              {{ scope.row.freeRoomCount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalRoomCount"
          label="总房间数"
          width="100"
          align="center"
        />
        <el-table-column
          prop="provinceName"
          label="所处省份"
          width="120"
          align="center"
        />
        <el-table-column prop="cityName" label="所处城市" width="120" align="center" />
        <el-table-column
          prop="districtName"
          label="所处区域"
          width="120"
          align="center"
        />
        <el-table-column prop="phone" label="联系方式" width="120" align="center" />
        <el-table-column prop="status" label="入住状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === '已满房' ? 'danger' : 'success'"
              effect="dark"
              class="status-tag"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isRelease" label="发布状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              :model-value="scope.row.isRelease === 1"
              inline-prompt
              :active-text="'是'"
              :inactive-text="'否'"
              @change="(val) => handlePublishChange(val, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon> <Edit /> </el-icon>修改
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row.id)">
              <el-icon> <Delete /> </el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增门店' : '编辑门店'"
      width="50%"
    >
      <el-form :model="formData" label-width="120px" :rules="formRules">
        <!-- 公寓名称 -->
        <el-form-item label="公寓名称">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <!-- 公寓介绍 -->
        <el-form-item label="公寓介绍">
          <el-input type="textarea" v-model="formData.introduction"></el-input>
        </el-form-item>
        <!-- 区域和城市信息 -->
        <el-form-item label="区域名称" @click="handleSelectAll">
          <el-cascader
            ref="cascaderRef"
            v-model="valueAll"
            :options="optionsAllCity"
            @change="handleRegionChange"
          />
        </el-form-item>
        <!-- 地址详情 -->
        <el-form-item label="详细地址">
          <el-input v-model="formData.addressDetail"></el-input>
        </el-form-item>
        <el-form-item label="地理位置">
          <MapPicker ref="mapPicker" />
        </el-form-item>
        <!-- 联系电话 -->
        <el-form-item label="联系电话">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>
        <!-- 是否发布 -->
        <el-form-item label="是否发布 (1/0)">
          <el-switch v-model="formData.isRelease" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <!-- 配套设施和其他信息 -->
        <el-form-item label="配套设施" @click="handleFacility">
          <el-select
            v-model="formData.facilityInfoIds"
            multiple
            placeholder="请选择配套设施"
            style="width: 240px"
          >
            <el-option
              v-for="item in optionsFacility"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" @click="handleLabel">
          <el-select
            v-model="formData.labelIds"
            multiple
            placeholder="请选择标签"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="杂费值" @click="handleFeeValue">
          <el-select
            v-model="formData.feeValueIds"
            multiple
            placeholder="请选择杂费值"
            style="width: 240px"
          >
            <el-option
              v-for="item in optionsFeeValue"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 图片信息 -->
        <el-form-item label="图片上传">
          <div class="upload-container">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              v-model:file-list="fileList"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :before-upload="beforeUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisibleImg">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button v-show="saveDialogVisible" type="primary" @click="onSubmit"
            >提交</el-button
          >
          <el-button v-show="updataDialogVisible" type="primary" @click="updataOnSubmit"
            >提交</el-button
          >
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import MapPicker from "@/components/MapPicker.vue";

import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";

// 搜索表单数据
const searchForm = reactive({
  districtId: "",
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const selectedRows = ref([]);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框数据
const dialogVisible = ref(false);
const dialogVisibleImg = ref(false);
const dialogType = ref("add");
const options = ref([]);
const optionsAllCity = ref([]);
const valueAll = ref([]);
const optionsFacility = ref([]);
const optionsFeeValue = ref([]);
const cascaderRef = ref([]);
const fileList = ref([]);
const updataDialogVisible = ref(false);
const saveDialogVisible = ref(false);
const dialogImageUrl = ref(""); // 图片预览地址
const formData = reactive({
  id: "",
  name: "",
  introduction: "",
  districtId: "",
  districtName: "",
  cityId: "",
  cityName: "",
  provinceId: "",
  provinceName: "",
  addressDetail: "",
  latitude: "",
  longitude: "",
  phone: "",
  isRelease: "",
  facilityInfoIds: [],
  labelIds: [],
  feeValueIds: [],
  graphVoList: [
    {
      name: "",
      url: "",
    },
  ],
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: "请输入门店名称", trigger: "blur" }],
  address: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],

  labelIds: [{ required: true, message: "请选择标签", trigger: "blur" }],

  totalRooms: [{ required: true, message: "请输入总房间数", trigger: "blur" }],
  contact: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
};
const mapPicker = ref(null);
const uploadRef = ref(null);

// API接口函数
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await request.get("/admin/apartment/pageItem", {
      params: {
        current: currentPage.value,
        size: pageSize.value,
      },
    });
    if (res.data.code === 200) {
      // 更新表格数据
      tableData.value = res.data.data.records || [];

      // 更新总条数
      total.value = res.data.data.total || 0;
    } else {
      ElMessage.error(res.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 添加初始化调用
onMounted(() => {
  fetchData();
});

// 搜索相关方法
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 表格操作方法
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};
// 新增门店
async function handleAdd() {
  dialogType.value = "add";
  dialogVisible.value = true;
  Object.keys(formData).forEach((key) => {
    formData[key] = "";
  });
  optionsAllCity.value = [];
  updataDialogVisible.value = false;
  saveDialogVisible.value = true;
}
// 编辑门店
const handleEdit = async (row) => {
  dialogType.value = "edit";
  dialogVisible.value = true;
  updataDialogVisible.value = true;
  saveDialogVisible.value = false;
  // 清空表单数据
  const byId =  await request.get("/admin/apartment/getDetailById", {
    params: {
      id: row.id,
    },
  });
  console.log(byId.data.data);
  formData.facilityInfoIds = byId.data.data.facilityInfoList.map(item => item.id)
  formData.labelIds = byId.data.data.labelInfoList.map(item => item.id)
  formData.feeValueIds = byId.data.data.feeValueVoList.map(item => item.id) // 假设有id字段
 // 正确赋值 Cascader 的绑定值（注意层级顺序）
 valueAll.value = [row.provinceId,row.districtId,row.cityId];
  formData.id = row.id;
  formData.name = row.name;
  formData.introduction = row.introduction;
  formData.districtId = row.districtId;
  formData.districtName = row.districtName;
  formData.addressDetail = row.addressDetail;
  formData.latitude = row.latitude;
  formData.longitude = row.longitude;
  formData.phone = row.phone;
  formData.isRelease = row.isRelease;

  fileList.value = byId.data.data.graphVoList.map((item) => ({
    name: item.name,
    url: item.url,
  }));
  handleFacility();
  handleLabel();
  handleFeeValue();
  handleSelectAll();

}
// 获取配套设施
async function handleFacility() {
  const reqFacility = await request.get("/admin/facility/list?type=1");
  if (reqFacility.data.code === 200) {
    optionsFacility.value = reqFacility.data.data.map((item) => ({
      value: item.id,
      label: item.name,
    }));
  }
}
// 获取标签
async function handleLabel() {
  // mapPicker.value.initMap();
  const reqLabel = await request.get("/admin/label/list?type=1");
  if (reqLabel.data.code === 200) {
    options.value = reqLabel.data.data.map((item) => ({
      value: item.id,
      label: item.name,
    }));
  }
}



// 获取杂费值
async function handleFeeValue() {
  const reqFeeValue = await request.get("/admin/fee/list");
  if (reqFeeValue.data.code === 200) {
    optionsFeeValue.value = reqFeeValue.data.data.map((item) => ({
      value: item.id,
      label: item.name,
    }));
  }
}
async function handleSelectAll() {
  try {
    const selectAll = await request.get("/admin/apartment/selectProvinceCityCounty");
    // console.log(selectAll.data.data);
    if (selectAll.data.code === 200 && Array.isArray(selectAll.data.data)) {
      optionsAllCity.value = selectAll.data.data.map((province) => ({
        value: province.id,
        label: province.name,
        children: province.cities.map((city) => ({
          value: city.id,
          label: city.name,
          children: city.counties.map((county) => ({
            value: county.id,
            label: county.name,
          })),
        })),
      }));
    } else {
      console.error("获取地区数据失败", selectAll.data);
    }
  } catch (error) {
    console.error("获取地区数据时发生错误:", error);
  }
}
const handleRegionChange = (selectedNodes) => {
  let casLabelVal = cascaderRef.value.getCheckedNodes(); // 获取选中的节点信息
  selectedNodes = casLabelVal;
  const labels = selectedNodes[0].pathLabels;
  const value = selectedNodes[0].pathValues;

  if (!Array.isArray(selectedNodes)) {
    console.error("selectedNodes is undefined or not an array");
    return;
  }

  if (!selectedNodes.length) {
    console.error("未选择任何区域");
    return;
  }

  // 提取各层级信息
  formData.provinceName = labels[0] || "";
  formData.provinceId = value[0] || "";
  formData.cityName = labels[2] || "";
  formData.cityId = value[2] || "";
  formData.districtName = labels[1] || "";
  formData.districtId = value[1] || "";
};
// 根据id删除
const handleDelete = (id) => {
  console.log("删除门店:", id);
  ElMessageBox.confirm("确定要删除该门店吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      const remove = await request.delete(`/admin/apartment/removeById?id=${id}`);
      if (remove.data.code === 200) {
        ElMessage.success("删除成功");
        fetchData();
      } else {
        ElMessage.error(remove.data.msg || "删除失败");
      }
    } catch (error) {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  });
};
// 发布状态切换
const handlePublishChange = async (val, row) => {
  try {
    await request.post(
      `/admin/apartment/updateReleaseStatusById?id=${row.id}&status=${val ? 1 : 0}`
    );
    row.isRelease = val ? 1 : 0;
    ElMessage.success("更新成功");
  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error("更新失败");
    row.isPublished = !val;
  }
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 图片上传前的钩子
const beforeUpload = () => {
  return false; // 阻止自动上传
};
function handleChange(file, fileList) {
  fileList.value = fileList;
}
function handlePictureCardPreview(uploadFile) {
  dialogImageUrl.value = uploadFile.url;
  dialogVisibleImg.value = true;
}
// 提交表单
const onSubmit = async () => {
  if (fileList.value.length > 0) {
    const files = fileList.value.map((item) => item.raw);
    const formPayload = new FormData();
    files.forEach((file) => {
      formPayload.append("file", file); // 关键修改：添加名为file的字段
    });
    try {
      const uploadResp = await request.post("/admin/file/upload", formPayload, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      console.log("uploadResp:", uploadResp);
      if (uploadResp.data.code === 200) {
        const url = uploadResp.data.data;
        formData.graphVoList = [
          {
            name: `图片_${new Date().getTime()}`,
            url: url,
          },
        ];
      } else {
        ElMessage.error(uploadResp.data.msg || "上传失败");
        return;
      }
    } catch (error) {
      console.error("上传失败:", error);
      ElMessage.error("上传失败");
      return;
    }
  }

  try {
    const { latitude, longitude } = mapPicker.value.getCoordinates();
    formData.latitude = latitude;
    formData.longitude = longitude;
    // 提交时直接使用存储的id数组，例如：
  const submitData = {
  ...formData,
  facilityInfoIds: formData.facilityInfoIds,
  labelIds: formData.labelIds,
  feeValueIds: formData.feeValueIds
}
    const req = await request.post("/admin/apartment/saveOrUpdate", submitData);
    if (req.data.code === 200) {
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(req.data.msg || "操作失败");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};
// 更新表单
async function updataOnSubmit() {
  dialogType.value = "updata";
  dialogVisible.value = true;
  const { latitude, longitude } = mapPicker.value.getCoordinates();
  formData.latitude = latitude;
  formData.longitude = longitude;
  // 更改值
  const submitData = {
    ...formData,
    facilityInfoIds: formData.facilityInfoIds,
    labelIds: formData.labelIds,
    feeValueIds: formData.feeValueIds
  }
  formData.graphVoList = fileList.value.map((item) => ({
    name: item.name,
    url: item.url,
  }));
  try {
    const req = await request.post("/admin/apartment/saveOrUpdate", submitData);
    if (req.data.code === 200) {
console.log("1111");
      console.log(submitData);
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(req.data.msg || "操作失败");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
}
</script>

<style scoped>
.upload-container {
  width: 100%;
}

:deep(.el-upload-list) {
  margin-top: 10px;
}

.image-list {
  margin-top: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.image-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  margin: 4px 0;
  background: #f5f7fa;
  border-radius: 4px;
}

.file-name {
  flex: 1;
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.apartment-container {
  padding: 20px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 0;
}

.operation-section {
  margin-bottom: 0;
  padding: 10px 20px;
  background: #fff;
  border-radius: 4px;
  border-top: 1px solid #ebeef5;
}

.pagination-section {
  margin-top: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.table-card {
  margin-top: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: bold;
  border-bottom: 2px solid #ebeef5;
  height: 50px;
  padding: 0;
  text-align: center;
}

:deep(.el-table__row) {
  padding: 8px 0;
  height: 50px;
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.room-count {
  font-weight: bold;
}

.low-count {
  color: #f56c6c;
}

.status-tag {
  min-width: 60px;
  text-align: center;
}

:deep(.el-switch) {
  --el-switch-on-color: #67c23a;
}

:deep(.el-button--link) {
  height: 28px;
  padding: 0 8px;
}

:deep(.el-button--link .el-icon) {
  margin-right: 4px;
  vertical-align: middle;
}

:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.9);
}

:deep(.el-table__empty-block) {
  min-height: 200px;
}

:deep(.el-table__empty-text) {
  color: #909399;
}

.fixed-height-table {
  height: 500px; /* 固定表格高度为 500px，可以根据需要调整 */
}
</style>
